
// 获取最大线程数量
export const MAX_THREAD_COUNT = navigator.hardwareConcurrency || 4;

export default function (workerUrl: string, postMessage: (worker: Worker, index: number) => any, onMessage: (worker: Worker, index: number) => ((this: Worker, ev: MessageEvent<any>) => any), threadCount: number = MAX_THREAD_COUNT) {
  for (let i = 0; i < threadCount; i++) {
    // 创建一个线程并分配任务
    const worker = new Worker(new URL(workerUrl, import.meta.url), {
      type: "module"
    })
    // 根据这个函数，获取一个要传递给worker的对象
    const pMsg = postMessage(worker, i);
    worker.postMessage(pMsg)
    // 根据onMessage生成一个worker.onmessage方法
    worker.onmessage = onMessage(worker, i)
  }
}